package com.example.roam.game.dujiangyan.game.control;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;

import com.example.roam.R;
import com.example.roam.game.app.dujiangyan.GameSecondDjyActivity;
import com.example.roam.game.app.dujiangyan.GameThirdDjyActivity;
import com.example.roam.game.app.jiuzhaigou.GameThirdJzgActvity;
import com.example.roam.game.dujiangyan.game.model.Dot;
import com.example.roam.game.dujiangyan.game.model.FinSpirit;
import com.example.roam.game.tools.CatchBadgeSpirit;
import com.example.roam.game.util.BeginSpirit;
import com.example.roam.game.util.GameConstant;
import com.example.roam.game.util.State;
import com.example.roam.utils.BadgeUtils;
import com.example.roam.utils.Constans;

import java.util.ArrayList;
import java.util.Random;

public class GameControl {
    private Context context;
    private static final int ROW = 10;
    private static final int COL = 10;
    private static final int BLOCKS = (int)((ROW*COL) * 0.1) ;
    private int width = (int)Math.floor(1000 / COL) ;
    private Dot martix[][];
    private Dot cat;
    private Paint paint;
    private Bitmap bitmap , humanBitmap , catBg ;
    private Rect catRect , humanRect;
    private int offsetDistance;
    private int bgYLocation = (int)(720*Constans.SCALE_HEIGHT);
    private FinState currentFinState = FinState.START;
    private FinSpirit finSpirit;
    private BeginSpirit beginSpirit;
    private Bitmap block , blockChoose , oval;
    private int clazz;
    private boolean isFinsh;
    private CatchBadgeSpirit catchBadgeSpirit;

    public enum FinState{
        LOSE,WIN,NONE,START;
    }

    // 1080 1793
    // x y / 100 的映射逻辑到数组上来控制touch。控制piant画不用状态
    // 画图只x,y的matrix有关paint。点击 x y / 100 的映射逻辑到数组上来控制touch
    // 放道士图片和精灵图片
    public GameControl(Context context){
        this.context = context;
        beginSpirit = new BeginSpirit(context,GameConstant.GAME_CATCH_SPIRIT);
        this.block = BitmapFactory.decodeResource(context.getResources(), R.drawable.block);
        this.blockChoose = BitmapFactory.decodeResource(context.getResources(),R.drawable.block_choose);
        this.paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        catchBadgeSpirit = new CatchBadgeSpirit(context, GameConstant.Qing_BADGE_C);
        initDotArray();
    }

    private void initDotArray(){
        martix = new Dot[ROW][COL];
        for (int i = 0; i < martix.length; i++) {
            for (int j = 0; j < martix[i].length; j++) {
                martix[i][j] = new Dot(i,j);
                martix[i][j].setStatus(Dot.STATUS_OFF); // 默认就是off，这部不用
            }
        }
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ghost);
        humanBitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.character_taoist);
        catBg = BitmapFactory.decodeResource(context.getResources(),R.drawable.cat_bg);
        humanRect = new Rect();
        catRect = new Rect();
        finSpirit = new FinSpirit(context);
    }

    private void randomDotBlock(){  // 随机dotArray10个障碍
        Random random = new Random();
        int block = 0;
        while ( block < BLOCKS ){
            int ranRow = random.nextInt(ROW);
            int ranCol = random.nextInt(COL);
            if( martix[ranRow][ranCol].getStatus() != Dot.STATUS_ON ){
                martix[ranRow][ranCol].setStatus(Dot.STATUS_ON);
                block ++;
            }
        }
    }

    private void initCatDot(){            // 初始化猫咪节点
        cat = new Dot(ROW/2,COL/2);
        cat.setStatus(Dot.STATUS_IN);
        martix[cat.getX()][cat.getY()].setStatus(Dot.STATUS_IN);
    }

    private void drawDotArray(Canvas canvas){
        canvas.drawBitmap(catBg,null,new Rect(0,0,(int)(1080*Constans.SCALE_WIDTH),(int)(1793*Constans.SCALE_HEIGHT) ),null);
        for (int i = 0; i < ROW; i++) {
            if( i % 2 != 0 ){
                offsetDistance = width / 2;
            }else {
                offsetDistance = 0;
            }
            for (int j = 0; j < COL; j++) {
                switch (martix[i][j].getStatus()){
                    case Dot.STATUS_OFF:
                        paint.setColor(Color.parseColor("#ffEEEEEE") );
                        oval = block;
                        break;
                    case Dot.STATUS_ON:
                        paint.setColor(Color.parseColor("#FFFFAA00"));
                        oval = blockChoose;
                        break;
                    case Dot.STATUS_IN:
                        paint.setColor(Color.parseColor("#ffEEEEEE") );
                        oval = block;
                        break;
                }
                // 按col画，i外层循环，j内层循环。 x不边，y一直变 [0][0],[0][1],[0][2]。因为width由y扩大，所以按列画
                // 已改成按row画

                int leftLocation = offsetDistance + j * width+5;
                int rightLocation = offsetDistance + ( j * width ) + width;
                int topLocation = bgYLocation+ i * width + 5;
                int bottomLocation = bgYLocation+(( i * width) +width );
                canvas.drawBitmap(oval,null,new Rect(leftLocation,topLocation,rightLocation,bottomLocation),paint);
                // 200 * 200 吧，以Location为下中
                if( martix[i][j].getStatus() == Dot.STATUS_IN ){
                    drawCat(leftLocation,rightLocation,topLocation,bottomLocation);
                }
            }
        }

        canvas.drawBitmap(bitmap,null,catRect,null);
        canvas.drawBitmap(humanBitmap,null,humanRect,null);
    }

    public void drawCat(int leftLocation,int rightLocation,int topLocation,int bottomLocation){
        catRect.set(leftLocation-(width/4)+(width/20),topLocation-width/2,rightLocation+(width/4)+(width/20),bottomLocation);
    }

    public void draw(Canvas canvas){     // x y / 100 的映射逻辑到数组上来控制touch。控制piant画不用状态
            drawDotArray(canvas);
            beginSpirit.draw(canvas);
            fin(canvas);
            catchBadgeSpirit.draw(canvas);
    }

    public void fin(Canvas canvas){
        finSpirit.draw(canvas);
    }

    public void onTouchDot(MotionEvent event){
        if( currentFinState == FinState.NONE) {
            int x = (int) event.getX();
            int y = (int) event.getY() - bgYLocation;
            int row = y / width;
            int col = x / width;
            if (row % 2 != 0) {
                x -= (width / 2);
                col = x / width;
            }
            if (row < 10 && col < 10) {
                if (martix[row][col].getStatus() == Dot.STATUS_OFF) {
                    martix[row][col].setStatus(Dot.STATUS_ON);
                    drawHuman(row, col);
                    catMove();
                }
            }
        }
        if( currentFinState != FinState.NONE && currentFinState != FinState.START ){
            clickOptionAgain(event);
            clickOptionReturn(event);
        }
        if( currentFinState == FinState.START){
            clickStartGame(event);
            clickGameDetail(event);
            clickDeleteDetail(event);
        }
    }

    private void drawHuman(int i,int j) {
        if (i % 2 != 0) {
            humanRect.set( (offsetDistance + j * width)   , bgYLocation+i * width -(width) , offsetDistance + (j * width) + width , bgYLocation+((i * width) + width));
        }else {
            humanRect.set(j * width,bgYLocation+i * width-(width)    ,(j * width) + width ,bgYLocation+((i * width) + width) );
        }
        // 开始界面，游戏背景，胜利提示框，失败提示框，再来一局按钮，返回按钮，人物，精灵
    }

    public void catMove(){
        if( cat.getX() == 0 || cat.getY() == 0 || cat.getX() == COL || cat.getY() == ROW ){         // 1. 判断猫是否到边界。 0 ,0,10,10就算lose
            this.currentFinState = FinState.LOSE;
            finSpirit.setCurrentState(currentFinState);
            finSpirit.isVisible = true;
            return;
        }
        ArrayList<Dot> dotArray = new ArrayList<>();
        for (int i = 0; i < 6; i++) {    // 获取猫周围六个点
            Dot dot = getNrighbour(i);
            if( dot.getStatus() == Dot.STATUS_OFF ){ // 如果猫周围六个点有可走状态，加入数组
                dotArray.add(dot);
            }
        }
        if( dotArray.size() == 0 ){
            currentFinState = FinState.WIN;
            finSpirit.setCurrentState(currentFinState);
            finSpirit.isVisible = true;
        }else {
            moveTo(dotArray);
        }
    }

    private void moveTo(ArrayList<Dot> dotArray) {
        // 我实际要让matrix改变
        martix[cat.getX()][cat.getY()].setStatus(Dot.STATUS_OFF);
        cat.setXY(dotArray.get(0).getX(),dotArray.get(0).getY());
        martix[cat.getX()][cat.getY()].setStatus(Dot.STATUS_IN);
    }

    private Dot getNrighbour( int i) {
        switch ( i ){
            case 0: // 要判断奇数行和偶数行。因为相对相邻格不同
                if( cat.getX() % 2 != 0 ) { // 5 不等于0 .是偶数行
                    return martix[cat.getX()][cat.getY()-1];
                }else {
                    return martix[cat.getX()][cat.getY()-1];
                }
            case 1:
                if( cat.getX() % 2 != 0 ){
                    return martix[cat.getX()-1][cat.getY()]; //
                }else {
                    return martix[cat.getX()-1][cat.getY()-1]; //
                }
            case 2:
                if( cat.getX() % 2 != 0 ) {
                    return martix[cat.getX()-1][cat.getY()+1]; //
                }else {
                    return martix[cat.getX()-1][cat.getY()]; //
                }
            case 3:
                if( cat.getX() % 2 != 0 ){
                    return martix[cat.getX()][cat.getY()+1];
                }else {
                    return martix[cat.getX()][cat.getY()+1];
                }
            case 4:
                if( cat.getX() % 2 != 0 ) {
                    return martix[cat.getX()+1][cat.getY()+1]; //
                }else {
                    return martix[cat.getX()+1][cat.getY()]; //
                }
            case 5:
                if( cat.getX() % 2 != 0) {
                    return martix[cat.getX()+1][cat.getY()]; //
                }else {
                    return martix[cat.getX()+1][cat.getY()-1]; //
                }
        }
        return null;
        // i j  控制位置。draw会适当width画出，
        /**
         *  matrix[i][j].getStatus == Dot.Status_OFF
         *  猫的移动，点击都是控制 matrix[][]
         * */
    }

    public void clickOptionAgain(MotionEvent event){
        if (finSpirit.getOptionAgainSpirit().getRect().contains((int)event.getX(),(int) event.getY())) {
            currentFinState = FinState.NONE;
            initDotArray();
            randomDotBlock();
            initCatDot();
            finSpirit.isVisible = false;
        }
    }

    public void waitToStartActivity(Intent intent){  // 1. 设置动画，结束，跳转。
        if(currentFinState == FinState.WIN){
            if ( // 徽章是何判断有无包括该索引，决定是否开启动画
                    catchBadgeSpirit.getImgBadge() == GameConstant.DU_BADGE_C &&!BadgeUtils.getBadges().getBadgeArray().contains(5)
            || catchBadgeSpirit.getImgBadge() == GameConstant.JZG_BADGE_C && !BadgeUtils.getBadges().getBadgeArray().contains(14)
            ) {
                catchBadgeSpirit.setStartAnimation(true); // 启动动画

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        isFinsh = true;
                        intent.putExtra("isFinsh",isFinsh);
                        context.startActivity(intent);
                        ((Activity)context).finish();

                    }
                }).start();

            }else {
                isFinsh = true;
                intent.putExtra("isFinsh",isFinsh);
                context.startActivity(intent);
                ((Activity)context).finish();
            }

        } else {
            intent.putExtra("isFinsh",false);
            isFinsh = true;
            context.startActivity(intent);
            ((Activity)context).finish();
        }
    }

    public void clickOptionReturn(MotionEvent event){
        if (finSpirit.getOptionReturnSpirit().getRect().contains((int) event.getX(),(int) event.getY())) {
            Intent intent = null;
            if( clazz == 0 ) {
                intent = new Intent(context, GameThirdDjyActivity.class);
                catchBadgeSpirit.setImgBadge(GameConstant.DU_BADGE_C);
            }else if(clazz == 1) {
                intent = new Intent(context, GameThirdJzgActvity.class);
                catchBadgeSpirit.setImgBadge(GameConstant.JZG_BADGE_C);
            }
            waitToStartActivity(intent);
        }

    }

    public boolean isFinsh() {
        return isFinsh;
    }

    public int getClazz() {
        return clazz;
    }

    public void setClazz(int clazz) {
        this.clazz = clazz;
    }

    /**
     * gamecontrol 有isfinsh控制刷新和传导
     * thirdActivity isFinsh控制游戏结
     * thirdcontrol isfinsh控制结束如何操作
     * */

    private void clickStartGame(MotionEvent event){
        if( beginSpirit.isVisible && beginSpirit.getStartRect().contains((int)event.getX(),(int)event.getY())){
            currentFinState = FinState.NONE;
            randomDotBlock();
            initCatDot();
            beginSpirit.isVisible = false;
        }
    }

    private void clickDeleteDetail(MotionEvent event){
        beginSpirit.clickDetailDelete(event);
    }

    private void clickGameDetail(MotionEvent event){
        beginSpirit.clickDetail(event);
    }

    public void setFinsh(boolean finsh) {
        isFinsh = finsh;
    }
}
